package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.uitls.ThreadLocalUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

public class WmInterceptor implements HandlerInterceptor {
    /**
     * 请求到达controller方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        //判断请求头中userId是否存在
        Optional<String> optional = Optional.ofNullable(userId);
        if (optional.isPresent()){
            //userId存在,则将userId存到threadLocal中
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            ThreadLocalUtils.setUser(wmUser);
        }
        return true;
    }

    /**
     * 请求执行完controller方法后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  {
        //执行完毕后清理threadLocal中的用户信息
        ThreadLocalUtils.removeUser();
    }

}
